<template>
	<div v-if="props.isPage" class="appointment-page">
		<div class="page-header">
			<h2>预约管理</h2>
			<el-button type="primary" @click="handlePrint">
				<el-icon><Printer /></el-icon>
				打印
			</el-button>
		</div>
		<!-- 页面模式的内容 -->
		<div class="page-content">
			<!-- 页面模式下隐藏选择框，显示固定信息 -->
			<div class="info-display">
                <div class="info-item">
                    <span class="label">门店：</span>
                    <cl-select 
                        class="appoint-item" 
                        v-model="currentShopId" 
                        :options="shopList" 
                        prop="status"
                        style="width: 200px;"
                        @change="onShopChange"
                    />
                </div>
				<div class="info-item">
					<span class="label">日期：</span>
					<cl-date-picker
						v-model="startDate"
						type="valueFormat"
						prop="status"
						valueFormat="'YYYY-MM-DD'"
						placeholder="选择开始日期"
					/>
				</div>
			</div>
			<!-- 预约表格部分 -->
			<div class="appointment-table">
				<table>
					<thead>
						<tr>
							<th>限制</th>
							<th v-for="(date, index) in weekDates" :key="index">
								<!-- 点击可以设置限额 -->
								<el-button type="info" @click="setLimit(index)">
									设置
								</el-button>
							</th>
						</tr>
					</thead>
					<thead>
						<tr>
							<th>时间</th>
							<th v-for="(date, index) in weekDates" :key="index">
								{{ getWeekDayText(date.weekDay) }}({{ date.dateStr }})
							</th>
						</tr>
					</thead>
					<tbody>
						<tr v-for="time in timeSlots" :key="time.value">
							<td class="time-column">{{ time.label }}</td>
							<td
                                v-for="(day, index) in 7"
                                :key="index"
                                class="time-slot"
                                :class="{
                                    available: time.availableSlots[index],
                                    unavailable: !time.availableSlots[index],
                                    limited: time.limitedSlots && time.limitedSlots[index], // 添加限制时段样式类
                                    selected: selectedTime === time.value && selectedDay === index,
                                    signed: time.appointmentInfo?.[index]?.appointmentStatus === 1, // 已经有了签到状态的样式绑定
                                    'can-sign':
                                        props.isPage &&
                                        time.appointments?.[index] &&
                                        time.appointmentInfo?.[index]?.appointmentStatus === 0,
                                    ...(time.classStyles && time.classStyles[index]
                                        ? { [time.classStyles[index]]: true }
                                        : {})
                                }"
                                :data-time="time.value"
                                :data-weekday="weekDates[index].weekDay"
                                @click="
                                    time.classId && time.classStyles && time.classStyles[index]
                                        ? handleClassSelect(time.classId)
                                        : handleTimeClick(time, index)
                                "
                            >
                                <span
                                    v-if="time.appointments && time.appointments[index]"
                                    class="class-name"
                                    @click.stop="openStudentEditDialog(time, index)"
                                >
                                    {{ time.appointments[index] }}
                                </span>
                            </td>
						</tr>
					</tbody>
				</table>
			</div>
		</div>
	</div>
	<el-dialog
		v-model="multiSelectDialogVisible"
		title="设置限制"
		:close-on-click-modal="false"
		:before-close="handleMultiSelectCancel"
	>
		<div class="time-selection">
			<!-- <div class="limit-input">
				<span>限制人数：</span>
				<el-input
				v-model.number="limitCount"
				type="number"
				min="1"
				placeholder="请输入限制人数"
				style="width: 150px;"
				/>
			</div> -->
			<div class="time-title">不可预约的时间：</div>
			<el-checkbox-group v-model="selectedTimeSlots" class="horizontal-checkbox-group">
				<div v-for="time in timeSlots" :key="time.value" class="time-checkbox">
				<el-checkbox :label="time.value">{{ time.label }}</el-checkbox>
				</div>
			</el-checkbox-group>
		</div>
		<template #footer>
			<el-button @click="handleMultiSelectCancel">取消</el-button>
			<el-button type="primary" @click="handleMultiSelectConfirm">确认</el-button>
		</template>
	</el-dialog>
</template>

<script lang="ts" setup>
import { ref, watch, onMounted, nextTick } from 'vue';
import { useDict } from '/$/dict';
import { useCool } from '/@/cool';
import { ElMessage, ElMessageBox, ElCheckboxGroup, ElCheckbox } from 'element-plus';
import { Printer } from '@element-plus/icons-vue';
import { useBase } from '/$/base';
import { useI18n } from 'vue-i18n';
import { useRoute } from 'vue-router';

const { service } = useCool();
const { dict } = useDict();
const { t } = useI18n();
const route = useRoute();
const shopList = ref([]);

const options = {
    shopList: [
        {
            label: '店铺1',
            value: 1
        },
        {
            label: '店铺2',
            value: 2
        }
    ]
}

const props = defineProps({
	modelValue: {
		type: Boolean,
		default: false
	},
	studentId: {
		type: Number,
		default: 0
	},
	isPage: {
		type: Boolean,
		default: true
	}
});

const emit = defineEmits(['update:modelValue', 'success']);

const visible = ref(false);
const currentDoctorId = ref('');
const currentShopId = ref('');
const selectedTime = ref('');
const startDate = ref(new Date().toISOString().split('T')[0]);
const doctorList = ref([]);
const timeSlots = ref([]);
const selectedDay = ref(-1);
const weekDates = ref([]);
// 添加新的响应式变量
const shopName = ref('');
const { user } = useBase();

// 学员列表弹窗控制
const SignListVisible = ref(false);
const loading = ref(false);
const students = ref([]);
const currentClassId = ref('');

// 添加响应式变量
const editDialogVisible = ref(false);
const selectedStudentId = ref({});

// 添加打开编辑对话框的方法
const openStudentEditDialog = (time, index) => {
	if (time.appointments?.[index] === '/') {
		ElMessage.error('该时间已被限制预约');
		return;
	}
	if (time.appointments?.[index] && time.appointmentInfo?.[index]) {
		// 处理多人预约情况
		if (Array.isArray(time.appointmentInfo[index])) {
			// 如果是多人预约，默认选择第一个
			selectedStudentId.value = time.appointmentInfo[index][0].studentId;
		} else {
			// 单人预约
			selectedStudentId.value = time.appointmentInfo[index].studentId;
		}
		editDialogVisible.value = true;
	}
};

// 监听组件挂载
onMounted(() => {
	if (props.isPage) {
		getCurrentUserInfo();
	}
    getShopList()
});


// 监听 modelValue 变化
watch(
	() => props.modelValue,
	val => {
		visible.value = val;
	}
);

// 监听 visible 变化
watch(
	() => visible.value,
	val => {
		emit('update:modelValue', val);
		if (!val) {
			resetForm();
		}
	}
);

// 监听选择变化
watch([startDate], ([newStartDate]) => {
	if (currentShopId.value && newStartDate) {
		calculateWeekDates(newStartDate);
		getAppointmentList();
	}
});

// 门店选择变化时重新获取数据
const onShopChange = () => {
	if (currentShopId.value && startDate.value) {
		calculateWeekDates(startDate.value);
		getAppointmentList();
	}
};

// 获取店铺列表
async function getShopList() {
	const res = await service.order.shop.getSelectList()
	shopList.value = res
}

// 修改获取当前用户信息的函数
async function getCurrentUserInfo() {
	if (props.isPage) {
        currentShopId.value = 4;
        currentDoctorId.value = 1;
		

		// 自动获取预约列表
		calculateWeekDates(startDate.value);
		getAppointmentList();
	}
}

// 计算一周的日期
async function calculateWeekDates(startDateStr: string) {
	const dates = [];
	const start = new Date(startDateStr);
	const limitArr = await service.appointment.info.getShopWeekLimit({
		shopId: currentShopId.value
	})
	console.log(limitArr)
	for (let i = 0; i < 7; i++) {
		const date = new Date(start);
		date.setDate(date.getDate() + i);
		dates.push({
			weekDay: date.getDay(),
			dateStr: `${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`,
			limit: limitArr.find(item => item.week === date.getDay())?.limit || '无',
			noSelectTimeStr: limitArr.find(item => item.week === date.getDay())?.time || ''
		});
	}

	weekDates.value = dates;
}

// 添加新的响应式变量
const multiSelectDialogVisible = ref(false);
const selectedTimeSlots = ref<string[]>([]);
const currentLimitIndex = ref(-1);
const limitCount = ref(0); // 新增：存储限制人数

// 设置限额
function setLimit(index) {
  currentLimitIndex.value = index;
  selectedTimeSlots.value = []; // 重置选中的时间
  multiSelectDialogVisible.value = true;
  limitCount.value = Number(weekDates.value[index].limit);
  // 根据已限制时间显示已经勾选的时间
  console.log('setLimit', weekDates.value[index].noSelectTimeStr)
  if (weekDates.value[index].noSelectTimeStr) {
    selectedTimeSlots.value = weekDates.value[index].noSelectTimeStr.split(',');
	console.log(selectedTimeSlots.value)
  }
}

// 添加处理多选确认的函数
async function handleMultiSelectConfirm() {
	if (limitCount.value < 0) {
		ElMessage.warning('请输入有效的限制人数');
		return;
	}
	let selectedTimesStr = ''
	if (selectedTimeSlots.value.length > 0) {
		selectedTimesStr = selectedTimeSlots.value.join(',');
	}
	const result = await service.appointment.info.updateShopWeekLimit({
		shopId: currentShopId.value,
		week: weekDates.value[currentLimitIndex.value].weekDay,
		limit: Number(limitCount.value),
		time: selectedTimesStr
	})
	if (result) {
		ElMessage.success('设置成功');
		weekDates.value[currentLimitIndex.value].limit = limitCount.value;
		weekDates.value[currentLimitIndex.value].noSelectTimeStr = selectedTimesStr;
		multiSelectDialogVisible.value = false;
        // 重新加载日历信息
        getAppointmentList();
	}
}

// 添加处理多选取消的函数
function handleMultiSelectCancel() {
  multiSelectDialogVisible.value = false;
}

// 获取星期几的文字
function getWeekDayText(day: number): string {
	const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
	return weekDays[day];
}

// 获取医生列表
async function getDoctorList(shopId: number) {
	const res = await service.doctor.info.getSelectlist({ shopId: shopId });
	if (res) {
		doctorList.value = res;
	}
}

function generateTimeSlots(startTime: string, endTime: string) {
	const slots = [];
	const start = new Date(`2000/01/01 ${startTime}`);
	const end = new Date(`2000/01/01 ${endTime}`);

	while (start <= end) {
		const hours = start.getHours().toString().padStart(2, '0');
		const minutes = start.getMinutes().toString().padStart(2, '0');
		const timeStr = `${hours}:${minutes}`;

		const availableSlots = new Array(7).fill(true);

		slots.push({
			label: timeStr,
			value: timeStr,
			availableSlots: availableSlots,
			appointments: new Array(7).fill(null)
		});

		start.setMinutes(start.getMinutes() + 60);
	}
	return slots;
}

async function getAppointmentList() {
    const startDateStr = new Date(startDate.value).toISOString().split('T')[0];
    const endDate = new Date(startDate.value);
    endDate.setDate(endDate.getDate() + 7);
    const endDateStr = endDate.toISOString().split('T')[0];

    const params = {
        date: startDateStr,
        endDate: endDateStr,
        shopId: currentShopId.value,
        doctorId: currentDoctorId.value
    };

    try {
        const resAppoint = await service.appointment.info.dateAppoint(params);
        // const resClass = await service.appointment.info.dateClass(params);
        // 初始化时间槽
        timeSlots.value = generateTimeSlots('09:00', '19:30');
        if (resAppoint) {
            // 处理已预约时间
            resAppoint.forEach(appointment => {
                const appointmentDateTime = new Date(appointment.appointmentTime);
                const timeStr = `${appointmentDateTime.getHours().toString().padStart(2, '0')}:${appointmentDateTime.getMinutes().toString().padStart(2, '0')}`;

                // 计算日期是否在当前周内
                const appointmentDate = appointmentDateTime.toISOString().split('T')[0];
                const dayIndex = weekDates.value.findIndex(date => {
                    const appointmentMonth = appointmentDate.substring(5, 7);
                    const appointmentDay = appointmentDate.substring(8, 10);
                    return date.dateStr === `${appointmentMonth}-${appointmentDay}`;
                });

                // 找到对应的时间槽并标记为不可用
                const timeSlot = timeSlots.value.find(slot => slot.value === timeStr);
                if (timeSlot && dayIndex !== -1) {
                    let displayName = appointment.userName || '未知预约人';
                    if (!props.isPage && displayName !== '未知预约人') {
                        if (displayName.length === 2) {
                            displayName = displayName.charAt(0) + '*';
                        } else if (displayName.length > 2) {
                            displayName = displayName.charAt(0) + '*' + displayName.substring(2);
                        }
                    }
                    // 检查是否为当前用户
                    if (appointment.appointmentType === 1) {
                        displayName = `${displayName}(复)`;
                    }
                    // 多人预约时用/分隔
                    if (timeSlot.appointments[dayIndex]) {
                        // 如果已有预约人，添加新预约人
                        timeSlot.appointments[dayIndex] += '/' + displayName;
                    } else {
                        // 如果没有预约人，直接设置
                        timeSlot.appointments[dayIndex] = displayName;
                    }
                    timeSlot.availableSlots[dayIndex] = false;
                    // 添加签到状态和预约ID
                    if (!timeSlot.appointmentInfo) timeSlot.appointmentInfo = {};
                    // 如果已有预约信息，创建数组存储多个预约
                    if (timeSlot.appointmentInfo[dayIndex]) {
                        if (!Array.isArray(timeSlot.appointmentInfo[dayIndex])) {
                            // 转换为数组
                            timeSlot.appointmentInfo[dayIndex] = [timeSlot.appointmentInfo[dayIndex]];
                        }
                        // 添加新预约信息
                        timeSlot.appointmentInfo[dayIndex].push({
                            id: appointment.id,
                            studentId: appointment.studentId || 0,
                            appointmentStatus: appointment.appointmentStatus || 0
                        });
                    } else {
                        // 如果没有预约信息，直接设置
                        timeSlot.appointmentInfo[dayIndex] = {
                            id: appointment.id,
                            studentId: appointment.studentId || 0,
                            appointmentStatus: appointment.appointmentStatus || 0
                        };
                    }
                }
            });
        }
        
        // 添加：处理被限制的时段
        weekDates.value.forEach((date, dayIndex) => {
            if (date.noSelectTimeStr) {
                const limitedTimes = date.noSelectTimeStr.split(',');
                limitedTimes.forEach(timeStr => {
                    const timeSlot = timeSlots.value.find(slot => slot.value === timeStr);
                    if (timeSlot && dayIndex !== -1) {
                        timeSlot.availableSlots[dayIndex] = false;
                        // 如果没有预约人信息，设置为特殊标记
                        if (!timeSlot.appointments[dayIndex]) {
                            timeSlot.appointments[dayIndex] = '/';
                        }
                        // 添加限制标记类
                        if (!timeSlot.limitedSlots) {
                            timeSlot.limitedSlots = [];
                        }
                        timeSlot.limitedSlots[dayIndex] = true;
                    }
                });
            }
        });
    } catch (error) {
        console.log('获取预约信息失败', error);
        ElMessage.error('获取预约信息失败');
    }
}

// 修改时间选择处理函数
function handleTimeSelect(time, dayIndex) {
	if (time.availableSlots[dayIndex]) {
		if (selectedTime.value === time.value && selectedDay.value === dayIndex) {
			selectedTime.value = '';
			selectedDay.value = -1;
		} else {
			selectedTime.value = time.value;
			selectedDay.value = dayIndex;
		}
	}
}

// 添加班级预约处理函数
async function handleClassSelect(classId: number) {
	if (props.isPage) {
		console.log('handleClassSelect', classId);
		// 页面模式下，触发查看班级事件
		viewStudents({ id: classId });
		return;
	}
	try {
		// 使用 Element Plus 的确认弹窗
		await ElMessageBox.confirm('是否确认预约该班级？', '预约确认', {
			confirmButtonText: '确认',
			cancelButtonText: '取消',
			type: 'warning'
		});

		// 用户确认后继续预约流程
		await service.class.classAppoint.appointClass({
			studentId: props.studentId,
			classId: classId
		});
		ElMessage.success('班级预约成功');
		visible.value = false;
		emit('success');
	} catch (error: any) {
		// 如果是用户取消，不显示错误提示
		if (error !== 'cancel') {
			ElMessage.error(error?.message || '班级预约失败');
		}
	}
}

// 修改预约确认函数
async function handleConfirmAppointment() {
	if (!selectedTime.value || selectedDay.value === -1) {
		ElMessage.warning('请选择预约时间');
		return;
	}

	// 使用选中日期对应的完整日期
	const selectedDateInfo = weekDates.value[selectedDay.value];
	if (!selectedDateInfo) {
		ElMessage.warning('日期选择有误');
		return;
	}

	// 从当前选中的日期信息构建完整日期
	const [month, day] = selectedDateInfo.dateStr.split('-');
	const currentYear = new Date().getFullYear();
	const dateStr = `${currentYear}-${month}-${day}`;

	const params = {
		studentId: props.studentId,
		date: dateStr,
		shopId: currentShopId.value,
		doctorId: currentDoctorId.value,
		time: selectedTime.value
	};

	try {
		await service.appointment.info.appoint(params);
		ElMessage.success('预约成功');
		visible.value = false;
		emit('success');
	} catch (error: any) {
		ElMessage.error(error.message || '预约失败');
	}
}

// 重置表单
function resetForm() {
	currentDoctorId.value = '';
	currentShopId.value = '';
	selectedTime.value = '';
	startDate.value = new Date().toISOString().split('T')[0];
	timeSlots.value = [];
}
function handlePrint() {
	// 确保内容已加载
	nextTick(() => {
		const printContent = document.querySelector('.appointment-table');
		if (printContent) {
			const originalContents = document.body.innerHTML;
			const printStyles = `
                <style>
                    @page {
						size: landscape;
						margin: 1cm;  /* 增加页面边距 */
					}
					.print-container {
						margin-bottom: 20px;
						text-align: center;
						padding: 0 2cm;  /* 添加左右内边距 */
					}
					.print-container table {
						width: 90%;  /* 调整表格宽度，不要占满整个页面 */
						border-collapse: collapse;
						border: 1px solid black;
						font-size: 14px;
						margin: auto;  /* 保持表格居中 */
					}
					.print-header {
						text-align: center;
						margin-bottom: 10px;
						display: inline-flex;  /* 改为 inline-flex */
						align-items: center;
						gap: 10px;  /* logo 和标题之间的间距 */
					}
					.print-logo {
						height: 30px;
						width: auto;
					}
					.print-title {
						font-weight: bold;
					}
                    /* 表格基础样式 */
                    .appointment-table table {
                        width: 100%;
                        border-collapse: collapse;
                        border: 1px solid black;
                    }
                    .appointment-table th,
                    .appointment-table td {
                        border: 1px solid black;
                        text-align: center;
                    }
                    /* 时间槽样式 */
                    .appointment-table .time-slot {
                        min-height: unset;
                        overflow: hidden;
                    }
                    .appointment-table .time-slot.available {
                        background-color: #333;
                    }
                    .appointment-table .time-slot.unavailable {
                        background-color: #eee;
                    }
                    /* 班级名称样式 */
                    .appointment-table .class-name {
                        white-space: nowrap;
                        overflow: hidden;
                        text-overflow: ellipsis;
                        max-width: 100%;
                        display: block;
                    }
                    /* 表头样式 */
                    .appointment-table thead th {
                        font-weight: normal;
                        white-space: nowrap;
                    }
                    /* 时间列样式 */
                    .appointment-table .time-column {
                        width: 8%;
                        background-color: #f5f7fa;
                    }
                </style>
                <div class="print-container">
					<div class="print-header">
						<img class="print-logo" src="https://joyballet.oss-cn-beijing.aliyuncs.com/eyemanager/logo/logo.png" alt="Logo">
						<div class="print-title">${shopName.value}预约名单-${startDate.value}</div>
					</div>
					${printContent.innerHTML}
				</div>
            `;
			document.body.innerHTML = printStyles;
			// 等待图片加载完成后再打印
			const logoImg = document.querySelector('.print-logo');
			if (logoImg) {
				logoImg.onload = () => {
					window.print();
					document.body.innerHTML = originalContents;
					location.reload();
				};

				// 添加错误处理
				logoImg.onerror = () => {
					console.error('Logo 加载失败');
					window.print();
					document.body.innerHTML = originalContents;
					location.reload();
				};
			} else {
				window.print();
				document.body.innerHTML = originalContents;
				location.reload();
			}
			// document.body.innerHTML = originalContents;
			// 重新挂载Vue应用
			// location.reload();
		}
	});
}

// 查看学员方法
async function viewStudents(row: any) {
	currentClassId.value = row.id;
	SignListVisible.value = true;
	loading.value = true;

	try {
		const res = await service.class.classAppoint.getClassStudents({
			classId: row.id
		});
		students.value = res;
		console.log('viewStudents', res, students);
	} catch (err) {
		ElMessage.error(t('获取学员列表失败'));
	} finally {
		loading.value = false;
	}
}
// 签到方法
async function handleSignIn(row: any) {
	try {
		// 添加确认弹窗
		await ElMessageBox.confirm(t('确认要为该学员签到吗？'), t('签到确认'), {
			confirmButtonText: t('确认'),
			cancelButtonText: t('取消'),
			type: 'info'
		});

		// 用户确认后继续签到流程
		await service.class.classAppoint.signIn({
			appointId: row.appointId
		});
		ElMessage.success(t('签到成功'));
		viewStudents({ id: currentClassId.value });
	} catch (err: any) {
		// 如果是用户取消操作，不显示错误提示
		if (err !== 'cancel') {
			ElMessage.error(err.message || t('签到失败'));
		}
	}
}

// 退班方法
async function handleQuit(row: any) {
	ElMessageBox.confirm(t('确认要将该学员退班吗？'), t('提示'), {
		type: 'warning'
	})
		.then(async () => {
			try {
				await service.class.classAppoint.cancelAppoint({
					id: row.appointId
				});
				ElMessage.success(t('退班成功'));
				viewStudents({ id: currentClassId.value });
			} catch (err: any) {
				ElMessage.error(err.message || t('退班失败'));
			}
		})
		.catch(() => {});
}

// 已到店
async function appointCome(id: number) {
	try {
		// 添加确认弹窗
		await ElMessageBox.confirm(t('确认要为该学员签到吗？'), t('签到确认'), {
			confirmButtonText: t('确认'),
			cancelButtonText: t('取消'),
			type: 'info'
		});

		// 用户确认后继续签到流程
		await Crud.value?.service.appointCome({ appointId: id });
		ElMessage.success('签到成功');
		// 刷新表格数据
		Crud.value?.refresh();
	} catch (err: any) {
		// 如果是用户取消操作，不显示错误提示
		if (err !== 'cancel') {
			ElMessage.error(err.message || '签到失败');
		}
	}
}
async function handleTimeClick(time, index) {
	if (props.isPage && time.appointments?.[index] && time.appointmentInfo?.[index]) {
		// 在页面模式下，如果是未签到的预约，执行签到
		if (time.appointmentInfo[index].appointmentStatus === 0) {
			try {
				await ElMessageBox.confirm('是否确认签到？', '签到确认', {
					confirmButtonText: '确认',
					cancelButtonText: '取消',
					type: 'info'
				});

				await service.appointment.info.appointCome({
					appointId: time.appointmentInfo[index].id
				});
				ElMessage.success('签到成功');
				// 更新签到状态
				time.appointmentInfo[index].appointmentStatus = 1;
				// 刷新预约列表
				getAppointmentList();
			} catch (error: any) {
				if (error !== 'cancel') {
					ElMessage.error(error?.message || '签到失败');
				}
			}
		} else if (time.appointmentInfo[index].appointmentStatus === 1) {
			try {
				await ElMessageBox.confirm('是否取消签到？', '取消确认', {
					confirmButtonText: '确认',
					cancelButtonText: '取消',
					type: 'info'
				});

				await service.appointment.info.appointCome({
					appointId: time.appointmentInfo[index].id
				});
				ElMessage.success('取消签到成功');
				// 更新签到状态
				time.appointmentInfo[index].appointmentStatus = 1;
				// 刷新预约列表
				getAppointmentList();
			} catch (error: any) {
				if (error !== 'cancel') {
					ElMessage.error(error?.message || '取消签到失败');
				}
			}
		}
		return;
	}

	// 原有的时间选择逻辑
	if (time.classId && time.classStyles && time.classStyles[index]) {
		handleClassSelect(time.classId);
	} else {
		handleTimeSelect(time, index);
	}
}
</script>

<style scoped>
.time-selection {
  max-height: 400px;
  overflow-y: auto;
  padding: 10px;
}
.horizontal-checkbox-group {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}
.time-checkbox {
  display: inline-block;
  margin-bottom: 8px;
}
.limit-input {
  margin-bottom: 15px;
  padding: 5px;
  background-color: #f5f5f5;
  border-radius: 4px;
}
.time-title {
  margin: 10px 0;
  font-weight: bold;
}
.time-slot.signed {
	background-color: #71b84e !important;
	color: #fff !important;
}

.time-slot.can-sign {
	cursor: pointer;
	position: relative;
}

.time-slot.can-sign:hover {
	background-color: #95d475;
	color: white;
}
.appoint-item {
	margin-top: 5px;
	margin-bottom: 20px;
}

/* 添加蓝色名字样式 */
.blue-name {
	color: #1890ff !important;
}

.timeList {
	margin-top: 20px;
}

.time-row {
	display: flex;
	justify-content: space-between;
	margin-bottom: 10px;
}

.time-slot {
	width: 45%;
	text-align: center;
	border-radius: 4px;
	cursor: pointer;
	background-color: #fff;
	border: 1px solid #dcdfe6;
}

.time-slot.available {
	background-color: #e1f3d8;
	color: #67c23a;
}

.time-slot.unavailable {
	background-color: #fde2e2;
}

/* 工作日早上时间段的特殊样式 - 确保优先级高于普通的 unavailable 样式 */
td[data-weekday='1'].time-slot.unavailable[data-time='09:00'],
td[data-weekday='2'].time-slot.unavailable[data-time='09:00'],
td[data-weekday='3'].time-slot.unavailable[data-time='09:00'],
td[data-weekday='4'].time-slot.unavailable[data-time='09:00'],
td[data-weekday='5'].time-slot.unavailable[data-time='09:00'],
td[data-weekday='1'].time-slot.unavailable[data-time='09:30'],
td[data-weekday='2'].time-slot.unavailable[data-time='09:30'],
td[data-weekday='3'].time-slot.unavailable[data-time='09:30'],
td[data-weekday='4'].time-slot.unavailable[data-time='09:30'],
td[data-weekday='5'].time-slot.unavailable[data-time='09:30'] {
	background-color: #f5f7fa !important; /* 使用灰色背景 */
	color: #909399 !important; /* 使用灰色文字 */
}
.time-slot.selected {
	background-color: #fff;
	border: 1px solid #409eff;
	color: #409eff;
}
.appointment-table {
	margin-top: 20px;
	overflow-x: auto;
	margin-bottom: 20px; /* 添加底部间距 */
}

table {
	width: 100%;
	table-layout: fixed; /* 添加这行确保列等宽 */
	border-collapse: collapse;
	border: 1px solid #dcdfe6;
}

th,
td {
	border: 1px solid #dcdfe6;
	padding: 3px;
	text-align: center;
	width: 12.5%; /* 设置每列宽度为相等的比例（100% / 8列） */
	overflow: hidden; /* 防止内容溢出 */
	text-overflow: ellipsis; /* 内容溢出时显示省略号 */
	white-space: nowrap; /* 防止内容换行 */
}

.time-column {
	background-color: #f5f7fa;
	font-weight: bold;
	width: 12.5%; /* 修改为与其他列相同的宽度 */
}

.time-slot {
	cursor: pointer;
	/* height: 40px; */
	transition: all 0.3s;
}

.time-slot.available {
	background-color: #e1f3d8;
	color: #67c23a;
}

.time-slot.unavailable {
	/* background-color: #fde2e2; */
	color: #f56c6c;
	/* cursor: not-allowed; */
}

/* 添加限制时段的样式 */
.time-slot.limited {
    background-color: #f5f7fa !important;
    color: #909399 !important;
    cursor: not-allowed;
}

.time-slot.selected {
	background-color: #fff;
	border: 2px solid #409eff;
	color: #409eff;
}

/* 修改课程占位的特殊样式 */
.time-slot.class-block {
	position: relative;
	cursor: not-allowed;
	border: 1px solid #dcdfe6;
}

.time-slot.class-block.available {
	background-color: #fff7e6; /* 柔和的黄色背景 */
	color: #e6a23c; /* 暖橙色文字，与黄色背景搭配 */
	cursor: pointer;
}

.time-slot.class-block.unavailable {
	background-color: #fde2e2;
	color: #f56c6c;
}

.time-slot.class-block.first {
	border-bottom: none;
	border-radius: 4px 4px 0 0;
}

.time-slot.class-block.middle {
	border-top: none;
	border-bottom: none;
	color: transparent;
}

.time-slot.class-block.last {
	border-top: none;
	border-radius: 0 0 4px 4px;
}

.time-slot.class-clickable {
	cursor: pointer !important;
}

.time-slot.class-block {
	position: relative;
	background-color: #fde2e2;
	color: #f56c6c;
	cursor: not-allowed;
	border: 1px solid #dcdfe6;
}

.time-slot.class-block .class-name {
	position: absolute;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
	z-index: 1;
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
	width: 90%;
}

/* 半格样式 */
.time-slot.half-slot {
	background: linear-gradient(to bottom, #fde2e2 50%, transparent 50%) !important;
	color: #f56c6c;
}

/* 添加页面模式的样式 */
.appointment-page {
	padding: 20px;
	background: #fff;
	min-height: 100vh; /* 设置最小高度为视口高度 */
	display: flex;
	flex-direction: column;
}

.page-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 20px;
}

.page-content {
	max-width: 1200px;
	margin: 0 auto;
	flex: 1;
	overflow-y: auto; /* 添加垂直滚动 */
	padding-bottom: 60px; /* 底部预留空间 */
}

.form-group {
	margin-bottom: 20px;
}

.page-footer {
	margin-top: 20px;
	text-align: right;
}

/* 添加信息显示样式 */
.info-display {
	margin-bottom: 20px;
	padding: 15px;
	background-color: #f5f7fa;
	border-radius: 4px;
}

.info-item {
	margin-bottom: 10px;
	display: flex;
	align-items: center;
}

.info-item:last-child {
	margin-bottom: 0;
}

.info-item .label {
	font-weight: bold;
	margin-right: 10px;
	min-width: 60px;
}

.info-item .value {
	color: #606266;
}
</style>
